package com.qs.oauth2.server.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;

/**
 * 测试资源服务和授权服务同属一个应用时，资源服务器通过DefaultTokenServices解析token
 */
@Configuration
@EnableResourceServer
public class MyResourceServerConfig  extends ResourceServerConfigurerAdapter {

    @Autowired
    private DefaultTokenServices defaultTokenServices;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .antMatchers("/user/**").access("#oauth2.hasScope('user_scope')")
                .anyRequest().authenticated();
    }

    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources
                //每一个资源服务都会定义一个资源id
                .resourceId("user_res")
                //可以直接使用defaultTokenServices完成资源请求携带的令牌校验（此时令牌存储在当前应用的内存中）
                .tokenServices(defaultTokenServices)
                .stateless(true);
    }
}
